var subPage = {
	setting: null,
	className: "dark",
	curDragNodes: null,
	autoExpandNode: null,
	newCount: 1,
	curTreeNode: null,
	
	initPage: function () {
		subPage.__initSetting();
		subPage.__loadTreeDatas();
		subPage.__gatherEvent();
		subPage.__createUploader();
	},
	
	rendingTree: function (/**Array*/treeDatas) {
		$.fn.zTree.init($("#treeDemo"), subPage.setting, treeDatas);
		$("#selectAll").bind("click", subPage.selectAll);
	},
	
	__gatherEvent: function () {
		$("#addNodeBtn").click(function () {
			subPage.__addNodesAjax();
		});
	},
	
	
	__createUploader: function () {
		var uploader = new plupload.Uploader({
			runtimes : 'html5,flash,silverlight,html4',
			browse_button : 'pickfiles',
			container: document.getElementById('container'),
			url : hostUrl + '/api/file/plupload',
			flash_swf_url : hostUrl + '/static/jquery/pluploader/Moxie.swf',
			silverlight_xap_url : hostUrl + '/static/jquery/pluploader/Moxie.xap',
			
			filters : {
				max_file_size : '10mb',
				mime_types: [
					{title : "Image files", extensions : "jpg,gif,png"}
				]
			},

			init: {
				PostInit: function() {

				},

				FilesAdded: function(up, files) {
					uploader.start();
				},

				UploadProgress: function(up, file) {
					console.log("当前进度" + file.percent + "%");
				},

				FileUploaded: function (up, file, res) {
					var data = res.response;
					data = JSON.parse(data);
					var paths = $("#picturesPath").val();
					$("#photo").attr("src", hostUrl + "/api/file/picture?filePath=" + data.data);
					subPage.curTreeNode.path = data.data;
					subPage.__updateNodesAjax(subPage.curTreeNode.getParentNode(), subPage.curTreeNode);
				},
				
				Error: function(up, err) {
					alert(err.code + ":" + err.message);
				}
			}
		});

		uploader.init();
	},
	
	__loadTreeDatas: function () {
		$.ajax({
			url: hostUrl + "/api/zTree/loadAllNodes",
			dataType: "json",
			type: "GET",
			success: function (res) {
				subPage.rendingTree(res.data);
			}
		});
	},
	
	__initSetting : function () {
		subPage.setting = {
			view: {
				addHoverDom: subPage.addHoverDom,
				removeHoverDom: subPage.removeHoverDom,
				selectedMulti: false
			},
			edit: {
				enable: true,
				editNameSelectAll: true,
				showRemoveBtn: subPage.showRemoveBtn,
				showRenameBtn: subPage.showRenameBtn,
				drag: {
					autoExpandTrigger: true,
					prev: subPage.dropPrev,
					inner: subPage.dropInner,
					next: subPage.dropNext
				}
			},
			data: {
				simpleData: {
					enable: true
				}
			},
			callback: {
				beforeDrag: subPage.beforeDrag,
				beforeEditName: subPage.beforeEditName,
				beforeRemove: subPage.beforeRemove,
				beforeRename: subPage.beforeRename,
				onDrag: subPage.onDrag,
				onRemove: subPage.onRemove,
				onRename: subPage.onRename,
				onDrop: subPage.onDrop,
				onClick: subPage.onClick
			}
		};
	},
	
	
	dropPrev: function (treeId, nodes, targetNode) {
		var pNode = targetNode.getParentNode();
		if (pNode && pNode.dropInner === false) {
			return false;
		} else {
			for (var i = 0, l = subPage.curDragNodes.length; i < l; i++) {
				var curPNode = subPage.curDragNodes[i].getParentNode();
				if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
					return false;
				}
			}
		}
		return true;
	},
	
	dropInner: function (treeId, nodes, targetNode) {
		if (targetNode && targetNode.dropInner === false) {
			return false;
		} else {
			for (var i = 0, l = subPage.curDragNodes.length; i < l; i++) {
				if (!targetNode && subPage.curDragNodes[i].dropRoot === false) {
					return false;
				} else if (subPage.curDragNodes[i].parentTId && subPage.curDragNodes[i].getParentNode() !== targetNode && subPage.curDragNodes[i].getParentNode().childOuter === false) {
					return false;
				}
			}
		}
		return true;
	},

	dropNext: function (treeId, nodes, targetNode) {
		var pNode = targetNode.getParentNode();
		if (pNode && pNode.dropInner === false) {
			return false;
		} else {
			for (var i = 0, l = subPage.curDragNodes.length; i < l; i++) {
				var curPNode = subPage.curDragNodes[i].getParentNode();
				if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
					return false;
				}
			}
		}
		return true;
	},
	
	onDrop: function (event, treeId, treeNodes, targetNode, moveType, isCopy) {
		subPage.__updateNodesAjax(targetNode, treeNodes[0]);
	},

	beforeDrag: function (treeId, treeNodes) {
		subPage.className = (subPage.className === "dark" ? "":"dark");
		for (var i = 0, l = treeNodes.length; i < l; i++) {
			if (treeNodes[i].drag === false) {
				subPage.curDragNodes = null;
				return false;
			} else if (treeNodes[i].parentTId && treeNodes[i].getParentNode().childDrag === false) {
				subPage.curDragNodes = null;
				return false;
			}
		}
		subPage.curDragNodes = treeNodes;
		return true;
	},
	
	beforeDragOpen: function (treeId, treeNode) {
		subPage.autoExpandNode = treeNode;
		return true;
	},
	
	onDrag: function (event, treeId, treeNodes) {
		console.log(treeNodes);
	},
	
	beforeEditName: function (treeId, treeNode) {
		subPage.className = (subPage.className === "dark" ? "":"dark");
		var zTree = $.fn.zTree.getZTreeObj("treeDemo");
		zTree.selectNode(treeNode);
		return confirm("进入节点 -- " + treeNode.name + " 的编辑状态吗？");
	},
	
	beforeRemove: function (treeId, treeNode) {
		subPage.className = (subPage.className === "dark" ? "":"dark");
		var zTree = $.fn.zTree.getZTreeObj("treeDemo");
		var flag = false;
		zTree.selectNode(treeNode);
		if (confirm("确认删除 节点 -- " + treeNode.name + " 吗？")) {
			flag = subPage.__deleteNodesAjax(treeNode.id);
		}
		return flag;
	},
	
	onRemove: function (e, treeId, treeNode) {
		
	},
	
	beforeRename: function (treeId, treeNode, newName, isCancel) {
		subPage.className = (subPage.className === "dark" ? "":"dark");
		if (newName.length == 0) {
			alert("节点名称不能为空.");
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			setTimeout(function(){zTree.editName(treeNode)}, 10);
			return false;
		}
		return true;
	},
	
	onRename: function (e, treeId, treeNode, isCancel) {
		if (!isCancel) subPage.__updateNodesAjax(treeNode.getParentNode(), treeNode);
	},
	
	onClick: function (event, treeId, treeNode, clickFlag) {
		subPage.curTreeNode = treeNode;
		var pNode = treeNode.getParentNode();
		$("#parentTreeName").html(pNode != null ? pNode.name : "无");
		$("#treeNodeName").html(treeNode.name);
		
		if (treeNode.path != null && treeNode.path != '' && treeNode.path.length > 0) {
			$("#photo").attr("src", hostUrl + "/api/file/picture?filePath=" + treeNode.path);
		} else {
			$("#photo").attr("src", hostUrl + "/static/img/1.jpg");
		}
	},
	
	showRemoveBtn: function (treeId, treeNode) {
		return !(treeNode.children && treeNode.children.length > 0);
	},
	
	showRenameBtn: function (treeId, treeNode) {
		return true;
	},
	
	addHoverDom: function (treeId, treeNode) {
		var sObj = $("#" + treeNode.tId + "_span");
		if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
		var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='新增下级节点' onfocus='this.blur();'></span>";
		sObj.after(addStr);
		var btn = $("#addBtn_" + treeNode.tId);
		if (btn) btn.bind("click", function() {
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			subPage.__addNodesAjax(treeNode);
			return false;
		});
	},
	
	removeHoverDom: function (treeId, treeNode) {
		$("#addBtn_" + treeNode.tId).unbind().remove();
	},
	
	selectAll: function () {
		var zTree = $.fn.zTree.getZTreeObj("treeDemo");
		zTree.setting.edit.editNameSelectAll =  $("#selectAll").attr("checked");
	},
	
	/**
	 * 新增节点（请求网络）
	 * 
	 * @param node
	 */
	__addNodesAjax: function (/**Node*/parentNode) {
		var data = {name: "new node"};
		var pId = null;
		if (parentNode && parentNode != null) {data.pId = parentNode.id; pId = parentNode.id}
		$.ajax({
			url: hostUrl + "/api/zTree/addNodes",
			type: "post",
			data: data,
			success: function (res) {
				if (!res.success) { alert(res.message); return; }
				
				var newNode = res.data;
				var zTree = $.fn.zTree.getZTreeObj("treeDemo");
				zTree.addNodes(parentNode, {id: newNode.id, pId: pId, name: newNode.name });
			}
		});
	},
	
	/**
	 * 修改节点（请求网络）
	 * 
	 * @param node
	 */
	__updateNodesAjax: function (/**Node*/parentNode, /**Node*/node) {
		var data = {id: node.id, name: node.name};
		if (parentNode && parentNode != null) data.pId = parentNode.id;
		if (node.path && node.path != null) data.path = node.path;
		$.ajax({
			url: hostUrl + "/api/zTree/updateNodes",
			type: "post",
			data: data,
			success: function (res) {
				if (!res.success) { alert(res.message); return; }
			}
		});
	},
	
	/**
	 * 删除节点（请求网络）
	 * 
	 * @param nodeId
	 */
	__deleteNodesAjax: function (/**int*/nodeId) {
		var flag = true;
		$.ajax({
			url: hostUrl + "/api/zTree/dropNodes",
			type: "post",
			data: {nodeId: nodeId},
			async: false,
			success: function (res) {
				flag = res.success;
				if (!res.success) { alert(res.message); return; }
			}
		});
		return flag;
	},
	
};

